package controller

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/mlogclub/simple"
	"webapp/model"
	"webapp/service"
)

type UserController struct {
	Ctx iris.Context
}

func (this *UserController) PostSignin() *simple.JsonResult {
	username := this.Ctx.FormValue("username")
	password := this.Ctx.FormValue("password")

	//var user model.User = model.User{
	//	UserName:sql.NullString{String:username, Valid:true},
	//	PassWord:password,
	//}

	user, err := service.UserService.SignIn(username, password)
	if err != nil {
		return simple.JsonErrorMsg(err.Error())
	}
	return this.GenerateLoginResult(user)
}

func (this *UserController) PostSignup() *simple.JsonResult {
	var (
		username   = this.Ctx.URLParamTrim("username")
		password   = this.Ctx.URLParamTrim("password")
		rePassword = this.Ctx.URLParamTrim("rePassword")
	)
	fmt.Println("aaaaa" + username)

	user, err := service.UserService.SignUp(username, password, rePassword)

	if err != nil {
		return simple.JsonErrorMsg(err.Error())
	}

	return this.GenerateLoginResult(user)

}

func (this *UserController) DeleteUser() *simple.JsonResult {
	var username = this.Ctx.URLParamTrim("username")

	err := service.UserService.Delete(username)
	if err != nil {
		return simple.JsonErrorMsg(err.Error())
	}

	return simple.JsonSuccess()
}

func (this *UserController) PostUpdateuser() *simple.JsonResult {
	var name = this.Ctx.PostValueTrim("username")
	var password = this.Ctx.PostValueTrim("password")
	t := service.UserService.GetByUserName(name)

	if t == nil {
		return simple.JsonErrorMsg("entity not found")
	}

	if len(password) > 0 {
		t.Password = simple.EncodePassword(password)
	}
	err := service.UserService.Update(t)

	if err != nil {
		return simple.JsonErrorMsg(err.Error())
	}

	return simple.JsonSuccess()
}

// user: login user, ref: 登录来源地址，需要控制登录成功之后跳转到该地址
func (this *UserController) GenerateLoginResult(user *model.User) *simple.JsonResult {

	return simple.NewEmptyRspBuilder().
		Put("user", user.Username.String).JsonResult()
}
